package vip.aster.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.aster.system.entity.SysRoleOrg;
import vip.aster.system.mapper.SysRoleOrgMapper;
import vip.aster.system.service.SysRoleOrgService;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色机构关系 服务实现类
 * </p>
 *
 * @author Aster
 * @since 2023-11-28 10:36
 */
@Service
@AllArgsConstructor
public class SysRoleOrgServiceImpl extends ServiceImpl<SysRoleOrgMapper, SysRoleOrg> implements SysRoleOrgService {
    private SysRoleOrgMapper sysRoleOrgMapper;

    @Override
    public List<String> getDataScopeList(String userId) {
        return sysRoleOrgMapper.getDataScopeList(userId);
    }

    @Override
    public List<String> getOrgIdList(String roleId) {
        if (StrUtil.isBlank(roleId)) {
            return ListUtil.empty();
        }
        LambdaQueryWrapper<SysRoleOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleOrg::getRoleId, roleId);
        List<SysRoleOrg> list = this.list(queryWrapper);
        return CollUtil.isEmpty(list) ? ListUtil.empty() : list.stream().map(SysRoleOrg::getOrgId).toList();
    }

    @Override
    public void deleteByRoleIdList(List<String> roleIds) {
        LambdaQueryWrapper<SysRoleOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysRoleOrg::getRoleId, roleIds);
        this.remove(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(String roleId, List<String> orgIdList) {
        // 数据库机构ID列表
        List<String> dbOrgIdList = this.getOrgIdList(roleId);

        // 需要新增的机构ID
        Collection<String> insertOrgIdList = CollUtil.subtract(orgIdList, dbOrgIdList);
        if (CollUtil.isNotEmpty(insertOrgIdList)){
            List<SysRoleOrg> orgList = insertOrgIdList.stream().map(orgId -> {
                SysRoleOrg entity = new SysRoleOrg();
                entity.setOrgId(orgId);
                entity.setRoleId(roleId);
                return entity;
            }).collect(Collectors.toList());

            // 批量新增
            this.saveBatch(orgList);
        }

        // 需要删除的机构ID
        Collection<String> deleteOrgIdList = CollUtil.subtract(dbOrgIdList, orgIdList);
        if (CollUtil.isNotEmpty(deleteOrgIdList)){
            LambdaQueryWrapper<SysRoleOrg> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysRoleOrg::getRoleId, roleId);
            queryWrapper.in(SysRoleOrg::getOrgId, deleteOrgIdList);

            this.remove(queryWrapper);
        }
    }
}
